import request from '@/utils/request'
import { removeLocalHistories, setLocalHistories } from '@/utils/storage'
import { RootThunkAction } from '..'
import { SearAction } from '../reducers/search'
type SuggestionList = {
  options: string[]
}
// 搜索列表
export function getSuggestList(keyword: string): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<SuggestionList>('/suggestion?q=' + keyword)
    console.log(res)
    let options = res.data.options
    if (!options[0]) {
      options = []
    }
    dispatch({
      type: 'search/saveSuggestions',
      payload: options,
    })
  }
}

// 清空推荐记录
export function clearSuggestions(): SearAction {
  return {
    type: 'search/closeSuggestios',
  }
}

// 搜索历史
export function addSuggestList(keyword: string): RootThunkAction {
  return async (dispatch, getState) => {
    let historys = getState().search.historys
    historys = historys.filter((item) => item !== keyword)
    if (historys.length > 10) {
      historys = historys.splice(0, 10)
    }
    historys = [keyword, ...historys]
    dispatch({
      type: 'search/addSuggeList',
      payload: historys,
    })
    setLocalHistories(historys)
  }
}

// 删除历史记录
export function clearHistories(): RootThunkAction {
  return async (dispatch) => {
    dispatch({ type: 'search/clearHistorys' })
    removeLocalHistories()
  }
}

// 获取搜索结果
export function getSearchResults(
  keyword: string,
  page: number
): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get('search', {
      params: {
        q: keyword,
        page,
        per_page: 10,
      },
    })
    console.log(res)
    dispatch({
      type: 'search/SearchResults',
      payload: res.data.results,
    })
  }
}
